package com.mall.common.validate;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author: xrj
 * @date: 2021/11/25 22:42
 * @description:
 */
public class ValidationUtils {
    private static final Validator VALIDATOR;
    private static final Validator VALIDATOR_FAST;

    static {
        //快速模式,检测到第一个验证失败参数时就停止验证,true启用,false关闭
        VALIDATOR = Validation.byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory().getValidator();
        VALIDATOR_FAST = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
    }

    /**
     * @param t      校验对象
     * @param groups 校验组
     * @return ValidResult
     */
    public static <T> ValidResult validateBean(T t, Class<?>... groups) {
        ValidResult result = new ValidResult();
        Set<ConstraintViolation<T>> violationSet = VALIDATOR_FAST.validate(t, groups);
        boolean hasError = violationSet != null && violationSet.size() > 0;
        result.setHasErrors(hasError);
        if (hasError) {
            for (ConstraintViolation<T> violation : violationSet) {
                result.addError(violation.getPropertyPath().toString(), violation.getInvalidValue(), violation.getMessage());
            }
        }
        return result;
    }

    /**
     * @param t        被验证的对象
     * @param failFast 快速失败(首个错误结束验证)
     * @param groups   校验组,一般为空
     * @param <T>      验证对象Class
     * @return 验证结果
     */
    public static <T> ValidResult validateBean(T t, boolean failFast, Class<?>... groups) {
        ValidResult result = new ValidResult();
        Set<ConstraintViolation<T>> violationSet;
        if (failFast) {
            violationSet = VALIDATOR_FAST.validate(t, groups);
        } else {
            violationSet = VALIDATOR.validate(t, groups);
        }
        boolean hasError = violationSet != null && violationSet.size() > 0;
        result.setHasErrors(hasError);
        if (hasError) {
            for (ConstraintViolation<T> violation : violationSet) {
                result.addError(violation.getPropertyPath().toString(), violation.getInvalidValue(), violation.getMessage());
            }
        }
        return result;
    }


    /**
     * 校验结果类
     */
    @Data
    public static class ValidResult {
        /**
         * 是否有错误
         */
        private boolean hasErrors;

        /**
         * 所有属性错误信息类集合
         */
        private List<ErrorMessage> errors;

        public ValidResult() {
            this.errors = new ArrayList<>();
        }

        /**
         * 获取结果中所有验证错误信息
         *
         * @return 字符串形式, 空格隔开
         */
        public String getErrorsStr() {
            StringBuilder sb = new StringBuilder();
            for (ErrorMessage error : errors) {
                sb.append(error.getPropertyName()).append(":").append(error.getMessage()).append("(").append(error.getPropertyValue()).append(")").append(";");
            }
            return sb.toString();
        }

        /**
         * 往验证结果集中添加验证错误属性信息
         *
         * @param propertyName
         * @param message
         */
        public void addError(String propertyName, Object propertyValue, String message) {
            this.errors.add(new ErrorMessage(propertyName, propertyValue, message));
        }

        /**
         * 获取去重之后的非法属性值，以逗号分隔
         *
         * @return 所有非法属性值的拼接字符串
         */
        public String getProperties() {
            return String.join(",", errors.stream().map(ErrorMessage::getPropertyName).collect(Collectors.toSet()));
        }
    }

    /**
     * 错误信息类
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class ErrorMessage {
        /**
         * 属性名
         */
        private String propertyName;
        /**
         * 校验值
         */
        private Object propertyValue;
        /**
         * 验证错误信息
         */
        private String message;

    }
}
